﻿using IMES.Common.Domain.SirModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;

namespace GlennQuigmire.API.Application.Commands
{
    public class InboundOrderAllDeleteHander : IRequestHandler<InboundOrderAllDeleteCommand, Result>
    {

        private readonly IBaseRepositorys<InboundOrder> inboundOrderRepository;
        private readonly IBaseRepositorys<InboundOrderProduct> inboundOrderProductRepository;
        private readonly IBaseRepositorys<Product> productRepository;

        public InboundOrderAllDeleteHander(IBaseRepositorys<InboundOrder> inboundOrderRepository, IBaseRepositorys<InboundOrderProduct> inboundOrderProductRepository, IBaseRepositorys<Product> productRepository)
        {
            this.inboundOrderRepository = inboundOrderRepository;
            this.inboundOrderProductRepository = inboundOrderProductRepository;
            this.productRepository = productRepository;
        }

        /// <summary>
        /// 删除入库单及其关联的入库单商品
        /// </summary>
        /// <param name="request">要删除的入库单Id</param>
        /// <param name="cancellationToken">允许取消异步</param>
        /// <returns>返回删除响应对象</returns>
        public Task<Result> Handle(InboundOrderAllDeleteCommand request, CancellationToken cancellationToken)
        {
            var result = new Result();
            int n = 0;
            string[] ids = request.Ids.Split(',');
            foreach (var id in ids)
            {
                var info = inboundOrderRepository.GetAll().FirstOrDefault(c => c.InboundOrderId == Convert.ToInt32(id));
                if (info != null)
                {
                    info.DeleteDate = true;
                   n+= inboundOrderRepository.Update(info);
                    var list = inboundOrderProductRepository.GetAll().Where(c => c.InboundOrderId == Convert.ToInt32(id)).ToList();
                    foreach (var item in list)
                    {
                        item.DeleteDate = true;
                        n += inboundOrderProductRepository.Update(item);
                        var info1 = productRepository.GetAll().FirstOrDefault(c => c.ProductId == item.ProductId);
                        if (info1!= null)
                        {
                            info1.InventoryStore += item.InboundOrderNum;
                            n += productRepository.Update(info1);
                        }
                    }
                }
            }
            result.Code = n;
            return Task.FromResult(result);

        }
    }
}
